/**
 * 显示加载数据
 */
var loading = "<center style='margin-top:20px;'><span style='font-size:12px;text-align:center;'><img src='images/loading.gif'/><br/><br/>正在加载数据, 请稍侯...</span></center>";

var request = {
		getQueryString : function(val) {
			var uri = window.location.search;
			var re = new RegExp("" + val + "=([^&?]*)", "ig");
			return ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 1))
					: null);
		}
	}

/**
 * 判断是否是IE浏览器
 * 
 * @return
 */
function isIE() {
	return navigator.appName.indexOf("Microsoft") >= 0;
};

function el(id) {
	return document.getElementById(id);
};

/**
 * 获取HTTP请求对象
 * 
 * @return
 */
function getXMLHttpRequest() {
	var xmlHttp_ = null;
	if (isIE()) {
		xmlHttp_ = new ActiveXObject("Microsoft.XMLHTTP");
	} else
		xmlHttp_ = new XMLHttpRequest();

	return xmlHttp_;
};

/**
 * 获取XML数据文档对象,以同步方式进行(不建议)
 * 
 * @param xmlURL_
 *            地址
 * @return XML文档对象
 */
function loadXMLDocument(xmlURL_) {

	var xmlDoc_ = loadXML(xmlURL_);

	if (xmlDoc_ == null)
		return null;

	return xmlDoc_.documentElement;
};

/**
 * 获取XML数据,以同步方式进行(不建议)
 * 
 * @param xmlURL_
 *            地址
 * @return XML数据
 */
function loadXML(xmlURL_) {

	if (xmlURL_ == "")
		return null;

	var xmlHttp_ = getXMLHttpRequest();
	var xmlDoc_ = "";

	var sArray = xmlURL_.split("?");
	var path = null;
	var reqBody = "";
	if (sArray == null)
		path = xmlURL_;
	if (sArray.length <= 1)
		path = xmlURL_;
	if (sArray.length == 2) {
		path = sArray[0];
		reqBody = sArray[1];
	}

	xmlHttp_.open("POST", encodeURI(path), false);
	xmlHttp_.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");
	xmlHttp_.send(reqBody);

	xmlDoc_ = xmlHttp_.responseXML;

	if (xmlDoc_ == null || xmlDoc_.documentElement == null) {
		return null;
	}

	return xmlDoc_;
};

/**
 * 获取文本,以同步方式进行(不建议)
 * 
 * @param textURL_
 *            地址
 * @return
 */
function loadText(textURL_) {
	var xmlHttp_ = getXMLHttpRequest();
	var text_ = "";

	xmlHttp_.open("POST", encodeURI(textURL_), false);
	xmlHttp_.send("");
	htmlDoc_ = xmlHttp_.responseText;
	if (text_ == null) {
		alert("数据错误，请检查网络情况或者数据地址是否有误！@" + textURL_);
		return null;
	}

	return text_;
};

/**
 * 把xml数据文档对象和xsl样式文档对象转换成文本
 * 
 * @param xmlDoc
 *            XML文档对象
 * @param xslDoc
 *            XSL文档对象
 * @return
 */
function parse(xmlDoc, xslDoc) {

	if (xmlDoc == null)
		return null;
	if (xslDoc == null)
		return null;
	try {
		if (isIE()) {
			return xmlDoc.transformNode(xslDoc);
		} else {
			var processor = new XSLTProcessor();
			processor.importStylesheet(xslDoc);
			var resultDocument = processor.transformToDocument(xmlDoc);
			var serializer = new XMLSerializer();
			return serializer.serializeToString(resultDocument);
		}
	} catch (e) {
		return null;
	}
};

/**
 * 异步提交数据
 * 
 * @param _xmlHttpRequest_
 *            http请求对象
 * @param _url_
 *            目标地址
 * @param _body_
 *            数据内容
 * @return
 */
function postData(_xmlHttpRequest_, _url_, _body_) {
	_xmlHttpRequest_.open("Post", encodeURI(_url_), true);

	_xmlHttpRequest_.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");

	_xmlHttpRequest_.send(_body_);

	return false;

};

/**
 * 同步提交数据
 * 
 * @param _url_
 *            目标地址
 * @param _body_
 *            数据
 * @return 处理结果码，处理消息
 */
function postDataSyn(_url_, _body_) {
	_xmlHttpRequest_ = getXMLHttpRequest();
	_xmlHttpRequest_.open("POST", encodeURI(_url_), false);
	_xmlHttpRequest_.setRequestHeader("Content-Type",
			"application/x-www-form-urlencoded");

	_xmlHttpRequest_.send(_body_);

	var xmlDoc_ = _xmlHttpRequest_.responseXML;

	if (!xmlDoc_) {
		alert("请求错误!");
		return 0;
	}

	xmlDoc_ = xmlDoc_.documentElement;
	var code = xmlDoc_.getElementsByTagName("Code");
	code = code[0].firstChild.nodeValue;
	var msg = xmlDoc_.getElementsByTagName("Description");
	msg = msg[0].firstChild.nodeValue;

	return code + msg;

};

/**
 * 提交form表单, 从yui借鉴。
 * 
 * @param formId
 *            form表单id
 * @return 消息(id+description)
 */
function postForm(form) {

	var oForm, oElement, oName, oValue, oDisabled, hasSubmit = false, data = [], item = 0, i, len, j, jlen, opt;

	if (typeof form == 'string') {
		oForm = (el(form) || document.forms[form]);
	} else if (typeof formId == 'object') {
		oForm = form;
	} else {
		return 0;
	}

	for (i = 0, len = oForm.elements.length; i < len; ++i) {
		oElement = oForm.elements[i];
		oDisabled = oElement.disabled;
		oName = oElement.name;

		var notAllowBlank = oElement.getAttribute("not-allow-blank");
		oValue = oElement.value;

		if (notAllowBlank == 'true' && (oValue == '' || oValue == 'undefined')
				|| oValue == null) {
			alert(oElement.getAttribute("text") + "不允许为空!");
			return 0;
		}

		if (!oDisabled && oName) {
			oName = encodeURIComponent(oName) + '=';
			oValue = encodeURIComponent(oElement.value);

			switch (oElement.type) {
			case 'select-one':
				if (oElement.selectedIndex > -1) {
					opt = oElement.options[oElement.selectedIndex];
					data[item++] = oName
							+ encodeURIComponent((opt.attributes.value && opt.attributes.value.specified) ? opt.value
									: opt.text);
				}
				break;
			case 'select-multiple':
				if (oElement.selectedIndex > -1) {
					for (j = oElement.selectedIndex, jlen = oElement.options.length; j < jlen; ++j) {
						opt = oElement.options[j];
						if (opt.selected) {
							data[item++] = oName
									+ encodeURIComponent((opt.attributes.value && opt.attributes.value.specified) ? opt.value
											: opt.text);
						}
					}
				}
				break;
			case 'radio':
			case 'checkbox':
				if (oElement.checked) {
					data[item++] = oName + oValue;
				}
				break;
			case 'file':
				// stub case as XMLHttpRequest will only send the file path
				// as a string.
			case undefined:
				// stub case for fieldset element which returns undefined.
			case 'reset':
				// stub case for input type reset button.
			case 'button':
				// stub case for input type button elements.
				break;
			case 'submit':
				if (hasSubmit === false) {
					if (this._hasSubmitListener && this._submitElementValue) {
						data[item++] = this._submitElementValue;
					} else {
						data[item++] = oName + oValue;
					}

					hasSubmit = true;
				}
				break;
			default:
				data[item++] = oName + oValue;
			}
		}
	}

	var _sFormData = data.join('&');

	return postDataSyn(oForm.action, _sFormData);

}

/**
 * 获取cookie
 * 
 * @param name
 *            cookie名称
 * @return
 */
function getCookie(name) {

	var start = document.cookie.indexOf(name + "=");

	var len = start + name.length + 1;

	if ((!start) && (name != document.cookie.substring(0, name.length))) {

		return null;

	}

	if (start == -1)
		return null;

	var end = document.cookie.indexOf(';', len);

	if (end == -1)
		end = document.cookie.length;

	return unescape(document.cookie.substring(len, end));

}

/**
 * 设置cookie
 * 
 * @param name
 *            cookie名称
 * @param value
 *            cookie值
 * @param expires
 *            过期时间,以天计算，如一天后过期，则设为1
 * @param path
 *            路径
 * @param domain
 *            域
 * @param secure
 * @return
 */
function setCookie(name, value, expires, path, domain, secure) {

	var today = new Date();

	today.setTime(today.getTime());

	if (expires) {

		expires = expires * 1000 * 60 * 60 * 24;

	}

	var expires_date = new Date(today.getTime() + (expires));

	document.cookie = name + '=' + escape(value) +

	((expires) ? ';expires=' + expires_date.toGMTString() : '') + // expires.toGMTString()

			((path) ? ';path=' + path : '') +

			((domain) ? ';domain=' + domain : '') +

			((secure) ? ';secure' : '');

}

/**
 * 删除cookie
 * 
 * @param name
 * @param path
 * @param domain
 * @return
 */
function deleteCookie(name, path, domain) {

	if (getCookie(name))
		document.cookie = name + '=' +

		((path) ? ';path=' + path : '') +

		((domain) ? ';domain=' + domain : '') +

		';expires=Thu, 01-Jan-1970 00:00:01 GMT';

}

/**
 * 重写html标签内容, 已异步的方式根据提供的数据和样式地址获取数据和样式，解析并显示在指定的HTML标签内部。
 * 
 * @param compId
 *            html标签id
 * @param xmlURL
 *            XML数据地址
 * @param xslURL
 *            XSL样式地址
 * @param isShowLoading
 *            是否显示加载数据界面
 * @return
 */
function paintComponent(compId, xmlURL, xslURL, isShowLoading) {

	if (!compId) {
		return;
	}

	var obj = el(compId);

	if (!obj) {
		return;
	}

	if (isShowLoading)
		obj.innerHTML = loading;

	if (xmlURL) {
		var req = getXMLHttpRequest();
		req.onreadystatechange = function() {
			paintComponentStep1(req, obj, xslURL);
		};

		postData(req, xmlURL, null, true);
		return;
	} else {
		if (xslURL) {
			var req2 = getXMLHttpRequest();
			req2.onreadystatechange = function() {
				paintComponentStep2(req2, obj);
			};

			postData(req2, xslURL, null, true);
		}
	}

}

function paintComponentStep1(XMLHttpReq, obj, xslURL) {
	if (XMLHttpReq.readyState == 4) {
		if (XMLHttpReq.status == 200) {
			var xmlDoc = XMLHttpReq.responseXML;

			if (!xmlDoc) {
				return;
			}

			if (xslURL) {
				var req = getXMLHttpRequest();
				req.onreadystatechange = function() {
					paintComponentStep2(req, obj, xmlDoc);
				};

				postData(req, xslURL, null, true);
			}
		}
	}
}

function paintComponentStep2(XMLHttpReq, obj, xmlDoc) {
	if (XMLHttpReq.readyState == 4) {
		if (XMLHttpReq.status == 200) {

			if (xmlDoc) {
				var xslDoc = XMLHttpReq.responseXML;

				if (!xslDoc) {
					return;
				}

				var html = parse(xmlDoc, xslDoc);
				obj.innerHTML = html;
			} else {
				var html2 = XMLHttpReq.responseText;
				obj.innerHTML = html2;
			}
		}
	}
}
